/**
 * AES加密工具
 *
 * @author liuyangguang.
 * @Date 15/10/17.
 */
import * as Crypto from 'crypto';
import CONFIG from '../config';

//加密公共密钥 32位
let keys = new Buffer(CONFIG.SSO_KEY, 'base64');    //默认的是 sso_key
const clearEncoding = 'utf8'; //编码设置
const algorithm = 'aes-256-ecb'; //加密方式
const cipherEncoding = 'base64'; //加密类型 base64/hex...

//向量
let iv = '';

export function encodeCipher(data, key?: string): string {
  try {
    let cipher = Crypto.createCipheriv(algorithm, key ? new Buffer(key, 'base64') : keys, iv);
    let cipherChunks = [];
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    return cipherChunks.join('');
  } catch (e) {
    return null;
  }
}

export function decodeCipher(data, key?: string): string {
  try {
    let cipherChunks = [data];
    let decipher = Crypto.createDecipheriv(algorithm, key ? new Buffer(key, 'base64') : keys, iv);
    let plainChunks = [];
    for (let i = 0; i < cipherChunks.length; i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));
    }
    plainChunks.push(decipher.final(clearEncoding));
    return plainChunks.join('');
  } catch (e) {
    console.log(e);
  }
}
